/**
 * 引入npm包
 */
const createError = require('http-errors');
const express = require('express');
//Node 自带模块 
const path = require('path');
const cookieParser = require('cookie-parser');
//处理日志
const logger = require('morgan');
const session = require('express-session')
//后端解决跨域问题
// const cors = require("cors");

/**
 * 引入路由
 */
const indexRouter = require('./routes/index');
const usersRouter = require('./routes/users');
const vueRouter = require('./routes/vue');


const app = express();

/**
 * NOTE: 后端解决跨域的两种方式
 * 插件 OR 中间件(可设置加一个特殊请求头才next - 保证安全)
 * 裸奔,任何人都可以访问
 */
/*
const cors = require("cors");
app.use(cors());
// 上为插件方案, 下为中间件方案 
const allowCorsDomain = (req, res, next) => {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "*");
  next();
}
app.use(allowCorsDomain)
*/

/**
 * view engine setup(包含首页和error的ejs模板)
 * 设置中间件:将views "拆分" 到根目录(__dirname) -- 访问时跳过views
 */
app.set('views', path.join(__dirname, 'views'));
// 设置ejs模板引擎<即html预编译>
app.set('view engine', 'ejs');

/**
 * 如果要使用多个静态资源目录，请多次调用 express.static 中间件函数
 * app.use(express.static('public')); <== 简写
 */
// app.use('/', express.static(path.join(__dirname, 'public')));
app.use('/', express.static(path.join(__dirname, 'public')));
// NOTE: 注意设置静态目录是否需要省略当前文件夹 - (第一个参数为省略或重命名)
// app.use(express.static(path.join(__dirname, 'public')));
// app.use(express.static(path.join(__dirname, 'public')));

app.set('trust proxy', 1) // trust first proxy
app.use(cookieParser());
app.use(session({
  secret: 'keyboard cat',
  resave: true,
  saveUninitialized: true,
  //一小时后过期
  cookie: { maxAge: 3600 * 1000 * 12 }
}))
// 日志中间件
app.use(logger('dev'));

/**
 * 这两句决定了可以通过req.body获取post请求的参数
 */
app.use(express.json());
app.use(express.urlencoded({ extended: false }));

/**
 * 自定义路由
 */
app.use('/', indexRouter);
app.use('/hybrid/users', usersRouter);
app.use('/hybrid/uni', vueRouter);

// catch 404 and forward to error handler
app.use(function (req, res, next) {
  next(createError(404)); app.set('trust proxy', 1) // trust first proxy
  app.use(session({
    secret: 'keyboard cat',
    resave: false,
    saveUninitialized: true,
    cookie: { secure: true }
  }))
});

// error handler
app.use(function (err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};
  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
